$(function(){
    formInit()
    headFn()
    toTop()
    //选矿样式重置
    ;(function(){
        $('.checkStyleIpt').each(function(){checkRes(this)})
        $('.checkStyleIpt').on('change',function(){checkRes(this)})
        function checkRes(that){
            var flag = $(that).is(':checked');
            if(flag){
                $(that).siblings('.checkStyle').addClass('checkStyleCurrent')
            }else{
                $(that).siblings('.checkStyle').removeClass('checkStyleCurrent')
            }
        }
    })()
})
//迷你打开
function miniOpen(that){
    window.MainObj = that;
    var miniEle = '<div class="MiniBox">'+
        '<div class="MiniLogIfrBox">'+
        '<iframe src="./miniLogin.html" class="MiniIfr"></iframe>' +
        '</div>'+
        '</div>';
    $('body').append(miniEle)
    $('body').addClass('ovfHiden');
}
//迷你关闭
function miniClose(){
    $('.MiniBox').remove();
    $('body').removeClass('ovfHiden');
}
//支付块块方法
function buyFn(){
    //购买选项切换
    $('.buyVipList li').on('click',function(){
        $(this).addClass('act').siblings('li').removeClass('act')
    })
    //支付流程轮播
    $('.ZfbOpenTip').ZfbOpenTip()
    buyMathChange()
}
function buyMaskShow(cla){
    $('.'+cla).fadeToggle(200)
}
function buyMaskHide(cla){
    $('.'+cla).fadeToggle()
}
function formInit() {
    $('form').attr("AutoComplete","off");
};
function headFn(){
    $('#headerSchTab li').on('click',function(){
        $(this).addClass('current').siblings('li').removeClass('current');
        $('#searchType').val($(this).attr('data-type'))
    })
    $('#Keyword').on('focus',function(){
        $('#placeholderLabel').hide()
    })
    $('#Keyword').on('input',function(){
        $('#placeholderLabel').hide()
    })
    $('#Keyword').on('blur',function(){
        if(!$(this).val()){
            $('#placeholderLabel').show()
        }
    })
    $('#loginState').on('mouseenter','.loginSuccess',function(){
        $(this).children('.headUserBox').stop().slideDown(200)
    })
    $('#loginState').on('mouseleave','.loginSuccess',function(){
        $(this).children('.headUserBox').stop().slideUp(200)
    })
}
function navfn(a){
    $('.nav-cate-head').on('mouseenter',function(){
        $('.cate_menu').show();
        $('.cate_pop .cate_part').eq(0).show().siblings('.cate_part').hide();
    })
    $('.cate_menu li').on('mouseenter',function(){
        var ind = $(this).index();
        $('.cate_pop .cate_part').eq(ind).show().siblings('.cate_part').hide();
    })
    $('.nav-cate').on('mouseleave ',function(){
        $('.cate_pop .cate_part').hide();
        if(a==1) $('.cate_menu').hide();
    })
    $('.cate_part').each(function(){
        if($(this).find('.cate_detail').length==1) $(this).width('380px');
    })
    if(a!=1) $('.cate_menu').show();
}

function selectorFn(){
    var num,_elearr = $('.selector .selectorLine');
    hideLine()
    console.log(num);
    if(num<=2){
        $('.selector .selectorMore').remove()
    }
    $('.selector .selectorMore span').on('click',function(){
        if(!$(this).hasClass('down')){
            _elearr.show();
            $(this).addClass('down').html('收起 <i></i>')
        }else if($(this).hasClass('down')){
            hideLine()
            $(this).removeClass('down').html('更多选项 <i></i>')
        }
    })
    function hideLine(){
        _elearr.each(function(i){
            if(i>2){
                $(this).hide();
            }
            num = i;
        })
    }

}
//添加序列化对象方法
jQuery.prototype.serializeObject=function(){
    var obj=new Object();
    $.each(this.serializeArray(),function(index,param){
        if(!(param.name in obj)){
            obj[param.name]=param.value;
        }
    });
    return obj;
};
//返回顶部
function toTop(){
    var winHeight = $(window).height(),footHei = 340;
    $(document).on('scroll',function(){
        var t =document.documentElement.scrollTop||document.body.scrollTop;
        if(t>winHeight*2&&$(".toTop").css('right')=='-50px'){
            $(".toTop").stop().animate({right:"0"},'slow');
        }else if(t<winHeight*2&&$(".toTop").css('right')=='0px'){
            $(".toTop").stop().animate({right:"-50px"},'slow');
        }
        if($(document).height() - t - winHeight-footHei <=0){
            $('.toTop').stop().css({position:'absolute', bottom:footHei+'px',right:0})
        }else if($(document).height() - t - winHeight-footHei >=0){
            $('.toTop').css({position:'fixed', bottom:'0'})
        }
    })
    $('.scrollTop').on('click',function(event){
        event.preventDefault();
        $('html, body').stop().animate({scrollTop:0},'slow');
    })
}

//密码，提示
function setpswEve(){
    var ele = $('.pswtip').children('input');
    $('form').on('click','.pswtip',function(){
        ele[0].focus()
    })
    ele.on('input',function(){
        var str = $(this).val().length;
        if(str!=0){
            $(this).parent().removeClass('pswtip')
        }else{
            $(this).parent().addClass('pswtip')
        }
    })
}

//显示错误消息
function errorTis(ele,text){
    var $errorPlacement = $('input[name ='+ele+']').addClass('error').parents('form').children('.errorPlacement'),
        errorId =  ele+'-error',
        errorEle =  $('#' + errorId);
    if(errorEle.length==0){
        $errorPlacement.prepend('<label class="error" id='+errorId+' for='+ele+'>'+text+'</label>')
    }else{
        errorEle.html(text).show();
    }
}

//获取验证码
function getCode(that, ele, codeType) {
    var mobile = $(that).parents('form').find('[name=' + ele + ']').val(), that = $(that), codeout, t = 60;
    if (!/^(((13[0-9]{1})|(15[0-35-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(mobile)) {
        return errorTis(ele, '请输入正确格式手机号');
    }
    if (!that.hasClass('act')) {
        _Ajaxgetcode()
        clearInterval(codeout);
        that.html('<span><i>'+t +'s</i>'+' 重新发送</span>').addClass('act');
        codeout = setInterval(function () {
            t-=1;
            that.html('<span><i>'+t +'s</i>'+' 重新发送</span>');
            if (t == 0) {
                that.html('获取验证码').removeClass('act');
                clearInterval(codeout);
            }
        }, 1000)
    }
    function _Ajaxgetcode() {
        $.ajax({
            type: "POST",
            url: "/checkcode/sendCheckcode",
            data: mobile + "=" + mobile + "&codeType=" + codeType,
            dataType: "json",
            success: function (data) {
                //if (data.code == 1000) {
                //    layer.msg('验证码发送成功', {icon: 1, time: 1000});
                //} else if (data.code == 1001) {
                //    errorTis(ele, data.msg);
                //    clearInterval(codeout)
                //    $(that).removeClass('act').html('获取验证码');
                //}
            }
        });
    }
}

//    留言隐藏显示
function addcomtTog(){
    $('.addcomtBox').toggle()
}

function echarData(obj){
    $('.echartsBox').each(function(i){
        var myChart = echarts.init($(this)[0]);
        var data =[];
        var dataArr= obj[i]['data'];
        for(var j =0;j<dataArr.length;j++){
            var dataObj = {};
            dataObj.name = obj[i]['name'][j];
            dataObj.type = 'line';
            dataObj.data = obj[i]['data'][j];
            data.push(dataObj)
        }
        var option = {
            title:{
                show:false
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a}<br/>{b} -- {c}'
            },
            xAxis: {
                type: 'category',
                data: obj[i]['xitem'],
                axisLine:{
                    show:false
                },
                axisTick:{
                    show:false
                },

            },
            textStyle:{
                color:'#999999'
            },
            grid: {
                top:'30',
                left: '10',
                right: '10',
                bottom: '20',
                containLabel: true
            },
            yAxis: {
                type: 'value',
                axisLine:{
                    show:false
                },
                axisTick:{
                    show:false
                },
                splitLine:{
                    show:true,
                    lineStyle:{
                        type:'dashed',
                        color:'#ececec'
                    }
                }
            },
            series:data
        };
        myChart.setOption(option);
    })
}

//select重置
jQuery.fn.extend({
    selectSty:function(){
        //$(this).each(function(){
        //    var $that = $(this);
        //    var selectele = $that.children('select');
        //    var dlele = '',ddele = '';
        //    var seed = selectele.val();
        //    selectele.find('option').each(function(i){
        //        var val = $(this).attr('value');
        //        var text = $(this).html();
        //        if(val==seed){
        //            dlele = '<span data-value="'+val+'" class="seled">'+text+'</span>';
        //            ddele+='<li data-value="'+val+'" class="act">'+text+'</li>'
        //        }else{
        //            ddele+='<li data-value="'+val+'">'+text+'</li>'
        //        }
        //    })
        //    $that.find('.selectDl').remove();
        //    $that.append('<div class="selectDl">'+dlele+'<ul>'+ddele+'</ul></div>');
        //    $that.children('.selectDl').children('.seled').width(selectele.width())
        //    $that.on('click','.seled',function(e){
        //        e.stopPropagation();
        //        $(this).siblings('ul').show();
        //        var actval = selectele.val()
        //        $(this).siblings('ul').find('li').each(function(){
        //            if($(this).attr('data-value')==actval){
        //                $(this).addClass('act').siblings('li').removeClass('act')
        //            }
        //        })
        //    })
        //    $that.on('click','li',function(e){
        //        var tex = $(this).html(),val = $(this).attr('data-value');
        //        if((val == selectele.val())){
        //            return;
        //        }
        //
        //        $(this).addClass('act').siblings('li').removeClass('act')
        //        $(this).parent('ul').siblings('.seled').attr('data-value',val).html(tex);
        //        $(this).parent('ul').hide();
        //        selectele.val(val).change();
        //    })
        //    $that.on('mouseenter','li',function(e){
        //        $(this).addClass('act').siblings('li').removeClass('act')
        //    })
        //})
        //$(document).on('click',function(e){
        //    $('.selectDl ul').hide();
        //})
    }
})


//分享
function openFenxiang($type,$title,$summary,$pic,$desc,$url){
    if($type === 'WX'){
        $('.weixinFenxiangBox').show();
        document.getElementById('weixinFenxiangBoxCImg').setAttribute('src','http://www.gbtags.com/gb/qrcode?t='+ ($url||document.location) +'&s=300')
        $('#wxBClose').on('click',function(){
            $('.weixinFenxiangBox').hide()
        });
        return;
    }
    var _shareUrl;
    var _Url =     encodeURIComponent($url||document.location);
    var _Title =   encodeURIComponent($title||document.title);
    var _Summary = encodeURIComponent($summary);
    var _Desc =    encodeURIComponent($desc);
    var _pics =    encodeURIComponent($pic);
    var _width= 800;
    var _height= 530;
    switch($type) {
        case 'WB':
            _shareUrl = 'http://service.weibo.com/share/share.php?url='+_Url+'&title='+_Title+' %20 '+_Summary+'&pic='+_pics+'&appkey=1974153790'
            break;
        case 'QQ':
            _shareUrl = 'http://connect.qq.com/widget/shareqq/index.html?url='+_Url+'&showcount=0&desc='+_Desc+'&summary='+_Summary+'&title='+_Title+'&site=质量在线&pics='+_pics;
            break;
        case 'QZ':
            _shareUrl = 'https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url='+_Url+'&showcount=1&site=质量在线&title='+_Title+'&desc='+_Desc+'&summary='+_Summary+'&pics='+_pics;
            break;
    }
    window.open(_shareUrl,'_blank','width='+_width+'+px,height='+_height+'+px,top='+(document.documentElement.clientHeight-_height)/2+'px,left='+(document.documentElement.clientWidth-_width)/2+'px,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=0');
}

//时间格式化
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//获取URL参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if(r != null) return decodeURI(r[2]);
    return '';
}
//字符查询
function isContains(maxStr, minStr) {
    return maxStr.indexOf(minStr) >= 0;
}

//支付页轮播
jQuery.fn.extend({
    ZfbOpenTip:function(){
        $(this).each(function(){
            var $that = $(this),
                $o = $(this).children('.one'),
                $t = $(this).children('.two'),
                inter,num=0;
            interFn()
            $that.on('mouseenter',function(e){
                clearInterval(inter)
            })
            $that.on('mouseleave',function(e){
                num = 0;
                interFn()
            })
            $o.on('click',function(e){
                _change(1)
            })
            $t.on('click',function(e){
                _change(0)
            })
            function interFn(){
                inter = setInterval(function(){
                    num++;
                    _change(num)
                },2500)
            }
            function _change(n){
                if(n%2==0){
                    $that.addClass('act')
                }else{
                    $that.removeClass('act')
                }
            }
        })
    }
})

//支付数字运算
function buyMathChange(){
    var $that = $('.buyMath'),
        $Money = $('#BeanmMoney'),
        $num = $that.children('.buyNumber'),
        $r = $that.children('.buyReduce'),
        $p = $that.children('.buyPlus'),
        _Man = 0;
    function inp(f){
        var act = $num.val()-0;
        if(f=='f'&&act>1){
            $num.val(act-1)
        }else if(f=='p'){
            $num.val(act+1)
        }
        _Man= $num.val()*0.8
        $Money.html(_Man.toFixed(1)+'元')
    }
    $r.on('click',function(){
        inp('f')
        disab()
    })
    $p.on('click',function(){
        inp('p')
        disab()
    })
    function disab(){
        if($num.val()<=1){
            $r.addClass('disabled')
        } else {
            $r.removeClass('disabled')
        }
    }
    $num.on('change',function(){
        var _val = parseInt($(this).val())
        $(this).val(isNaN(_val)?1:_val)
        _Man= $num.val()*0.8
        $Money.html(_Man.toFixed(1)+'元')
    })
}

//是否要迷你登录
function JudgeMiniLogin(callback){
    if(typeof callback == "function"){
        this.uniqueCallback = callback;
    }else{
        this.uniqueCallback = function(){}
    }
    var userState=getLoginUser();
    if(!!userState){
        this.uniqueCallback();
    }else{
        miniOpen(this)
    }
}
JudgeMiniLogin.prototype.publicCallback=function(data){
    changeHead(data)
}

//判断是否登录
function getLoginUser(){
    var userState=false;
    ////1、通过异步判断
    //    $.ajax({
    //        type: "get",
    //        async: false,
    //        url: "/ajax/user/checkLogin",
    //        crossDomain: true,
    //        dataType: "json",
    //        success: function (data) {
    //            //用户已登录
    //            if (data.code == 1000) {
    //                userState = true;
    //            }
    //        }
    //    });
    return userState;
}

//    只负责改变头部信息
function changeHead(data){
    var hadEle = '<div class="loginSuccess dis-i pos-r"> ' +
        '<a href="javascript:;" class="headUserName i">'+data.name+'</a> ' +
        '<div class="headUserBox"> ' +
        '<ul class="headUserList"> ' +
        '<li class="huList1"><a href="./user-info.html"><span></span>账号管理</a></li> ' +
        '<li class="huList2"><a href="./user-price-list.html"><span></span>我的询价</a></li> ' +
        '<li class="huList3"><a href="./user-follow-goods.html"><span></span>我的关注</a></li> ' +
        '<li class="huList4"><a href="./user-comment.html"><span></span>我的留言</a></li> ' +
        '<li class="huList5"><a href="./user-download.html"><span></span>我的下载</a></li> ' +
        '<li class="huList6"><a href="javascript:;"><span></span>退出</a></li> ' +
        '</ul> ' +
        '</div> ' +
        '</div>';
    $('#loginState').empty().html(hadEle)
}
/**
 * 关注方法
 * @param targetId，要收藏的目标ID
 * @param favoritesFlag，类型，1：商品，2：价格，3：标准，4：供应商
 * @param targetUrl，目标URL
 */
function addLike(targetId, favoritesFlag,targetUrl) {
    if(!targetUrl){
        targetUrl="";
    }
    /**
     * 先判断登录
     */
    new JudgeMiniLogin(function (result) {
        $.ajax({
            url: "/ajax/favorites/add",
            type: "post",
            data: {
                targetId: targetId,
                favoritesFlag: favoritesFlag,
                targetUrl:targetUrl
            },
            success: function (data) {
                if (data.code == 1000) {
                    $('.like').html('<em></em>已关注').addClass('act');
                } else {
                    $('.like').html('<em></em>关注').removeClass('act');
                }
            }
        });
    })
}